package com.jereh.topnews.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jereh.topnews.R;
import com.jereh.topnews.api.NewsApi;
import com.jereh.topnews.callback.CallBack;
import com.jereh.topnews.db.ChannelDao;
import com.jereh.topnews.entity.Channel;
import com.jereh.topnews.util.RequestUtil;

import java.util.ArrayList;

public class WelcomeActivity extends AppCompatActivity implements CallBack{

    private RequestUtil util;
    private ArrayList<Channel> list=new ArrayList<>();
    private SharedPreferences sp;
    private ChannelDao channelDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        sp=getSharedPreferences("set",MODE_PRIVATE);
        channelDao=new ChannelDao(this);
        //判断本地数据库中是否包含频道数据，如果不存在
        if(channelDao.count()==0) {
            //联网获取频道数据
            getChannelByNet();
        } else {
            //如果存在数据，就执行activity跳转
            activityJump();
        }

    }

    /**
     * 联网获取频道数据
     */
    private void getChannelByNet() {
        util=new RequestUtil(this,this);
        util.setDataByUrl(NewsApi.CHANNEL_URL);
    }

    private void activityJump(){
        Intent intent=new Intent();
        if(sp.getBoolean("first",true)) {
            SharedPreferences.Editor editor=sp.edit();
            editor.putBoolean("first", false);
            editor.commit();
            intent.setClass(this,GuildActivity.class);
        } else {
            intent.setClass(this, NewsMainActivity.class);
        }
        startActivity(intent);
        finish();
    }

    @Override
    public void callback(String json) {
        try {
            //Map：存储键值对数据的集合
            JSONObject object = JSON.parseObject(json);

            JSONObject body = (JSONObject) object.get("showapi_res_body");
            //List<Map>:一组有序不唯一的集合数据
            JSONArray channelList=body.getJSONArray("channelList");
            list.addAll(JSON.parseArray(channelList.toJSONString(), Channel.class));
            //联网获取完数据，保存到本地数据库
            channelDao.addAll(list);
            //保存完毕，执行跳转
            activityJump();
        } catch (Exception e) {
            e.printStackTrace();
            errorCallback();
        }
    }

    @Override
    public void errorCallback() {
        Toast.makeText(WelcomeActivity.this, "网络异常，请稍后重试", Toast.LENGTH_LONG).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        },3000);
    }

}
